/*
 * =====================================================================================
 *
 *       Filename:  CompareAndExchangeVal.h
 *
 *    Description:  CompareAndExchangeVal.h
 *
 *
 *         Author:  Younghyun Jo
 *   Organization:  Master Student
 *                  Computer Systems and Platforms Laboratory
 *                  Department of Computer Science and Engineering
 *
 * =====================================================================================
 */

#ifndef PARTICIPANT
  #define PARTICIPANT Participant
#endif

#include <tmc/spin.h>
#include <tmc/sync.h>
#include <arch/atomic.h>
#include <arch/inline.h>
#include <sys/time.h>

#define spin_lock_init(lock) tmc_spin_mutex_init(lock)
#define spin_lock_destruct(lock) {;} // nothing
#define spin_lock_acquire tmc_spin_mutex_lock
#define spin_lock_release tmc_spin_mutex_unlock
#define spin_lock_t tmc_spin_mutex_t

class Participant;

class CompareAndExchangeVal {
  public:
    CompareAndExchangeVal(const int numParticipants) {}
    ~CompareAndExchangeVal() {}

    inline void finalize_initialization() {}

    int sharedVar;
};

class Participant {
  public:
    Participant(CompareAndExchangeVal* const compareAndExchangeVal)
      : _compareAndExchangeVal(compareAndExchangeVal) {}

    inline bool synchronize() const {
      int prevVal = _compareAndExchangeVal->sharedVar;
      int newVal = prevVal + 1;
      int val = arch_atomic_val_compare_and_exchange(&(_compareAndExchangeVal->sharedVar), prevVal, newVal);
      return true;
    }

  private:
    CompareAndExchangeVal* const _compareAndExchangeVal;
};

